package cms.web.action.common;


import cms.bean.ErrorView;
import cms.bean.mediaProcess.MediaProcessQueue;
import cms.bean.message.Remind;
import cms.bean.payment.PaymentLog;
import cms.bean.redEnvelope.GiveRedEnvelope;
import cms.bean.setting.EditorTag;
import cms.bean.setting.SystemSetting;
import cms.bean.thumbnail.Thumbnail;
import cms.bean.topic.*;
import cms.bean.user.*;
import cms.common.data.ApiResult;
import cms.manage.user.*;
import cms.service.access.*;
import cms.service.access.model.RedEnvelope;
import cms.service.mediaProcess.MediaProcessService;
import cms.service.message.RemindService;
import cms.service.setting.SettingService;
import cms.service.template.TemplateService;
import cms.service.thumbnail.ThumbnailService;
import cms.service.topic.TagService;
import cms.service.topic.TopicIndexService;
import cms.service.topic.TopicService;
import cms.service.upload.FileService;
import cms.service.user.UserGradeService;
import cms.service.user.UserService;
import cms.utils.Base64;
import cms.utils.*;
import cms.utils.threadLocal.AccessUserThreadLocal;
import cms.manage.AccessSourceDeviceManage;
import cms.web.action.SystemException;
import cms.web.action.fileSystem.FileManage;
import cms.manage.SensitiveWordFilterManage;
import cms.manage.FollowManage;
import cms.web.action.message.RemindManage;
import cms.web.action.payment.PaymentManage;
import cms.web.action.redEnvelope.RedEnvelopeManage;
import cms.manage.SettingManage;
import cms.manage.TopicManage;
import cms.web.html.FilterContent;
import cms.web.html.HtmlTypeEnum;
import cms.web.html.TextFilterManage;
import cms.web.taglib.Configuration;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * 话题接收表单
 */
@Controller
@RequestMapping("user/control/topic")
public class TopicFormAction {
	@Resource
	TemplateService templateService;

	@Resource
	AccountManage accountManage;
	@Resource
	AccessSourceDeviceManage accessSourceDeviceManage;
	@Resource
	TextFilterManage textFilterManage;
	@Resource
	SettingManage settingManage;
	@Resource
	SettingService settingService;
	@Resource
	UserService userService;
	@Autowired
	private HttpSession session;
	@Resource TopicService topicService;
	@Resource TagService tagService;
	@Resource PointManage pointManage;
	
	@Resource TopicIndexService topicIndexService;


	@Resource TopicManage topicManage;
	@Resource SensitiveWordFilterManage sensitiveWordFilterManage;
	@Resource ThumbnailService thumbnailService;
	@Resource UserManage userManage;
	
	@Resource RemindService remindService;
	@Resource RemindManage remindManage;
	@Resource FileManage fileManage;
	@Resource UserGradeService userGradeService;
	@Resource UserDynamicManage userDynamicManage;
	@Resource FollowManage followManage;
	
	@Resource UserRoleManage userRoleManage;
	@Resource PaymentManage paymentManage;
	@Resource MediaProcessService mediaProcessService;
	@Resource RedEnvelopeManage redEnvelopeManage;
	@Autowired
	CaptchaAccessService captchaAccessService;
	@Autowired
	CsrfTokenAccessService csrfTokenAccessService;
	@Autowired
	SystemActAccessService systemActAccessService;
	@Autowired
	RedEnvelopeAccessService redEnvelopeAccessService;
	@Autowired
	SubmitQuantityAccessService submitQuantityAccessService;
	
	/**
	 * 话题  添加
	 * @param model
	 * @param tagId 标签Id
	 * @param title 标题
	 * @param content 内容
	 * @param type 红包类型
	 * @param totalAmount 总金额
	 * @param singleAmount 单个金额
	 * @param giveQuantity 发放数量
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String add(ModelMap model,@RequestParam Long tagId,@RequestParam String title,@RequestParam String content,
			Integer type,BigDecimal totalAmount,BigDecimal singleAmount,Integer giveQuantity,
			String token,String captchaKey,String captchaValue,String jumpUrl,
			RedirectAttributes redirectAttrs,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		//获取登录用户
		AccessUser accessUser = AccessUserThreadLocal.get(session);

		boolean isAjax = WebUtil.submitDataMode(request);//是否以Ajax方式提交数据

		ApiResult apiResult = systemActAccessService.access(accessUser,"topic",request,tagId);
		if(!apiResult.isSuccess()){
			if (isAjax == true) {
				response.setStatus(403);//设置状态码
				WebUtil.writeToWeb("", "json", response);
				return null;
			} else {
				String dirName = templateService.findTemplateDirCache();
				String accessPath = accessSourceDeviceManage.accessDevices(request);
				request.setAttribute("message", "权限不足");
				return "templates/" + dirName + "/" + accessPath + "/message";
			}
		}

		csrfTokenAccessService.access(accessUser,"topic",request,token);

		ApiResult<Boolean> captchaResult = captchaAccessService.access(accessUser,"topic",request,captchaKey,captchaValue);
		RedEnvelope redEnvelope = new RedEnvelope(false,type,totalAmount,singleAmount,giveQuantity);
		redEnvelopeAccessService.access(accessUser,"topic",request,redEnvelope);

		Map<String, String> error = new HashMap<String, String>();

		SystemSetting systemSetting = settingService.findSystemSettingCache();
				
		
		Topic topic = new Topic();
		Date d = new Date();
		topic.setPostTime(d);
		topic.setLastReplyTime(d);

		//前台发表话题审核状态
		if(systemSetting.getTopic_review().equals(10)){//10.全部审核 20.特权会员未触发敏感词免审核(未实现) 30.特权会员免审核 40.触发敏感词需审核(未实现) 50.无需审核
			topic.setStatus(10);//10.待审核 	
		}else if(systemSetting.getTopic_review().equals(30)){
			boolean isPermission = userRoleManage.isPermission(ResourceEnum._1006000, tagId, accessUser);//是否有当前功能操作权限
			if (isPermission) {
				topic.setStatus(20);//20.已发布
			} else {
				topic.setStatus(10);//10.待审核
			}
		}else{
			topic.setStatus(20);//20.已发布
		}

		List<Tag> tagList = tagService.findAllTagCache();
		if(tagList != null && tagList.size() >0){
			for(Tag tag : tagList){
				if(tag.getId().equals(tagId)){
					topic.setTagId(tag.getId());
					topic.setTagName(tag.getName());
					break;
				}

			}
			if(topic.getTagId() == null){
				error.put("tagId", "标签不存在");
			}
		}
		if(title != null && !"".equals(title.trim())){
			if(title.length() > 150){
				error.put("title", "不能大于150个字符");
			}
			if(systemSetting.isAllowFilterWord()){
				String wordReplace = "";
				if(systemSetting.getFilterWordReplace() != null){
					wordReplace = systemSetting.getFilterWordReplace();
				}
				title = sensitiveWordFilterManage.filterSensitiveWord(title, wordReplace);
			}
			topic.setTitle(title);
		}else{
			error.put("title", "标题不能为空");
		}

		FilterContent filterContent = null;
		List<ImageInfo> beforeImageList =null;

		if(content != null && !"".equals(content.trim())){
			
		//	content = "<div style=\"text-align: center; height: expression(alert('test &ss')); while: expression(alert('test xss'));\">fdfd</div>";
		//	content = "<img src=\"java script:alert(/XSS/)\" width = 100>";
		//	content = "<div style=\"background-image: url(javasc \n\t ript:alert('XSS'))\">";
		//	content = "<img src=\"java\nscript:alert(/XSS/)\" width = 100>";
			
		//	content = "<div style=\"background-color: #123456;color: expr\65ssion(alert('testss'));\"><a href=\"javascript:alert('XSS');\"><a href=\"http://127.0.0.1:8080/cms/javascript:alert('XSS');\"><a href=\"aaa/ggh.htm\">";

			//	content = "<div style=\"background-image: url(javascript:alert('XSS'));background-image: url(javascript&colon;alert('XSSW'));width: expression(alert&#40;'testxss'));\">";
			//	content = "<div style=\"background-image: url(javasc\n\tript:alert('XSS'))\">";

			//	content = "<div style=\"color:express/**/ion(eval('\\x69\\x66\\x28\\x77\\x69\\x6e\\x64\\x6f\\x77\\x2e\\x61\\x21\\x3d\\x31\\x29\\x7b\\x61\\x6c\\x65\\x72\\x74\\x28\\x2f\\x73\\x74\\x79\\x6c\\x65\\x5f\\x38\\x2f\\x29\\x3b\\x77\\x69\\x6e\\x64\\x6f\\x77\\x2e\\x61\\x3d\\x31\\x3b\\x7d'))\">";

			EditorTag editorTag = settingManage.readTopicEditorTag();
			//过滤标签
			content = textFilterManage.filterTag(request, content, editorTag);
			filterContent = textFilterManage.filter(request, content, "topic", editorTag, HtmlTypeEnum.ALL);
			String value = filterContent.getContent();

			List<UserGrade> userGradeList = userGradeService.findAllGradeCache();
			//校正隐藏标签
			String validValue = textFilterManage.correctionHiddenTag(value, userGradeList);

			//允许使用的隐藏标签
			List<Integer> allowHiddenTagList = new ArrayList<Integer>();
			if (editorTag.isHidePassword()) {
				//是否有当前功能操作权限
				boolean isPermission = userRoleManage.isPermission(ResourceEnum._1020000, topic.getTagId(), accessUser);
				if (isPermission) {
					//输入密码可见
					allowHiddenTagList.add(HideTagType.PASSWORD.getName());
				}
			}
			if(editorTag.isHideComment()){
				//是否有当前功能操作权限
				boolean isPermission = userRoleManage.isPermission(ResourceEnum._1021000, topic.getTagId(), accessUser);
				if (isPermission) {
					//评论话题可见
					allowHiddenTagList.add(HideTagType.COMMENT.getName());
				}
			}
			if(editorTag.isHideGrade()){
				//是否有当前功能操作权限
				boolean isPermission = userRoleManage.isPermission(ResourceEnum._1022000, topic.getTagId(), accessUser);
				if (isPermission) {
					//达到等级可见
					allowHiddenTagList.add(HideTagType.GRADE.getName());
				}
			}
			if(editorTag.isHidePoint()){
				//是否有当前功能操作权限
				boolean isPermission = userRoleManage.isPermission(ResourceEnum._1023000, topic.getTagId(), accessUser);
				if (isPermission) {
					//积分购买可见
					allowHiddenTagList.add(HideTagType.POINT.getName());
				}
			}
			if(editorTag.isHideAmount()){
				//是否有当前功能操作权限
				boolean isPermission = userRoleManage.isPermission(ResourceEnum._1024000, topic.getTagId(), accessUser);
				if (isPermission) {
					//余额购买可见
					allowHiddenTagList.add(HideTagType.AMOUNT.getName());
				}
			}

			//解析隐藏标签
			Map<Integer,Object> analysisHiddenTagMap = textFilterManage.analysisHiddenTag(validValue);
			for (Map.Entry<Integer,Object> entry : analysisHiddenTagMap.entrySet()) {
				if(!allowHiddenTagList.contains(entry.getKey())){
					error.put("content", "发表话题不允许使用 '"+HideTagName.getKey(entry.getKey())+"' 隐藏标签");//隐藏标签
					break;
				}
			}
			
			//删除隐藏标签
			String newContent = textFilterManage.deleteHiddenTag(value);

			//不含标签内容
			String text = textFilterManage.filterText(textFilterManage.specifyHtmlTagToText(newContent));
			//清除空格&nbsp;
			String trimSpace = cms.utils.StringUtil.replaceSpace(text).trim();
			//摘要
			if(trimSpace != null && !"".equals(trimSpace)){
				if(systemSetting.isAllowFilterWord()){
					String wordReplace = "";
					if(systemSetting.getFilterWordReplace() != null){
						wordReplace = systemSetting.getFilterWordReplace();
					}
					trimSpace = sensitiveWordFilterManage.filterSensitiveWord(trimSpace, wordReplace);
				}
				if(trimSpace.length() >180){
					topic.setSummary(trimSpace.substring(0, 180)+"..");
				}else{
					topic.setSummary(trimSpace+"..");
				}
			}
			
			//不含标签内容
			String sourceText = textFilterManage.filterText(content);
			//清除空格&nbsp;
			String sourceTrimSpace = cms.utils.StringUtil.replaceSpace(sourceText).trim();


			if(filterContent.isUploadFile() || (!"".equals(sourceText.trim()) && !"".equals(sourceTrimSpace))){
				if(systemSetting.isAllowFilterWord()){
					String wordReplace = "";
					if(systemSetting.getFilterWordReplace() != null){
						wordReplace = systemSetting.getFilterWordReplace();
					}
					validValue = sensitiveWordFilterManage.filterSensitiveWord(validValue, wordReplace);
				}
				topic.setIp(IpAddress.getClientIpAddress(request));
				topic.setUserName(accessUser.getUserName());
				topic.setIsStaff(false);
				topic.setContent(validValue);
			}else{
				error.put("content", "话题内容不能为空");
			}

			//图片地址
			beforeImageList = new ArrayList<ImageInfo>();
			//非隐藏标签内图片
			List<String> otherImageNameList = textFilterManage.readImageName(newContent,"topic");
			
			if(CollectionUtils.isNotEmpty(otherImageNameList)){
				for(int i=0; i<otherImageNameList.size(); i++){
					ImageInfo imageInfo = new ImageInfo();
					imageInfo.setName(FileUtil.getName(otherImageNameList.get(i)));
					imageInfo.setPath(FileUtil.getFullPath(otherImageNameList.get(i)));
					beforeImageList.add(imageInfo);
				}
				topic.setImage(JsonUtils.toJSONString(beforeImageList));
				
			}
		}else{
			error.put("content", "话题内容不能为空");
		}
			
		if(error.size() == 0){
			//发红包金额日志
			PaymentLog giveRedEnvelopePaymentLog = null;
			GiveRedEnvelope giveRedEnvelope = null;
			if(redEnvelope.isHaveRedEnvelope()){
				if(type.equals(20)){//红包类型 20.公共随机红包(随机金额)
					giveRedEnvelope = new GiveRedEnvelope();
					
					giveRedEnvelope.setId(UUIDUtil.getUUID32());
					giveRedEnvelope.setUserId(accessUser.getUserId());
					giveRedEnvelope.setType(type);//类型
					giveRedEnvelope.setTotalAmount(redEnvelope.getTotalAmount());//红包总金额
					
					giveRedEnvelope.setGiveQuantity(redEnvelope.getGiveQuantity());//红包发放数量
					giveRedEnvelope.setRemainingQuantity(redEnvelope.getGiveQuantity());//剩余数量
				//	giveRedEnvelope.setBindTopicId(topic.getId());/插入话题表后设置
					giveRedEnvelope.setGiveTime(d);
					giveRedEnvelope.setDistributionAmountGroup(JsonUtils.toJSONString( redEnvelopeManage.createRedEnvelopeAmount(redEnvelope.getTotalAmount(),redEnvelope.getGiveQuantity())));
				}else if(type.equals(30)){//红包类型 30.公共定额红包(固定金额)
					giveRedEnvelope = new GiveRedEnvelope();
					giveRedEnvelope.setId(UUIDUtil.getUUID32());
					giveRedEnvelope.setUserId(accessUser.getUserId());
					giveRedEnvelope.setType(type);//类型
					giveRedEnvelope.setTotalAmount(redEnvelope.getTotalAmount());//红包总金额
					giveRedEnvelope.setSingleAmount(redEnvelope.getSingleAmount());//单个红包金额
					giveRedEnvelope.setGiveQuantity(redEnvelope.getGiveQuantity());//红包发放数量
					giveRedEnvelope.setRemainingQuantity(redEnvelope.getGiveQuantity());//剩余数量
				//	giveRedEnvelope.setBindTopicId(topic.getId());//插入话题表后设置
					giveRedEnvelope.setGiveTime(d);
				}
			}
			if(giveRedEnvelope != null){
				giveRedEnvelopePaymentLog = new PaymentLog();
				giveRedEnvelopePaymentLog.setPaymentRunningNumber(paymentManage.createRunningNumber(accessUser.getUserId()));//支付流水号
				giveRedEnvelopePaymentLog.setPaymentModule(120);//支付模块 120.发红包
				giveRedEnvelopePaymentLog.setSourceParameterId(giveRedEnvelope.getId());//参数Id
				giveRedEnvelopePaymentLog.setOperationUserType(2);//操作用户类型  0:系统  1: 员工  2:会员
				giveRedEnvelopePaymentLog.setOperationUserName(accessUser.getUserName());//操作用户名称  0:系统  1: 员工  2:会员
				giveRedEnvelopePaymentLog.setAmountState(2);//金额状态  1:账户存入  2:账户支出
				giveRedEnvelopePaymentLog.setAmount(redEnvelope.getTotalAmount());//金额
				giveRedEnvelopePaymentLog.setInterfaceProduct(0);//接口产品
				giveRedEnvelopePaymentLog.setUserName(accessUser.getUserName());//用户名称
				giveRedEnvelopePaymentLog.setTimes(d);
				
				topic.setGiveRedEnvelopeId(giveRedEnvelope.getId());//发红包Id
			}
			
			try {
				//保存话题
				topicService.saveTopic(topic,giveRedEnvelope, accessUser.getUserName(), redEnvelope.getTotalAmount(), giveRedEnvelopePaymentLog);
			} catch (SystemException e) {
				error.put("topic", e.getMessage());//提交话题错误
			}
			
			//更新索引
			topicIndexService.addTopicIndex(new TopicIndex(String.valueOf(topic.getId()),1));

			PointLog pointLog = new PointLog();
			pointLog.setId(pointManage.createPointLogId(accessUser.getUserId()));
			pointLog.setModule(100);//100.话题
			pointLog.setParameterId(topic.getId());//参数Id 
			pointLog.setOperationUserType(2);//操作用户类型  0:系统  1: 员工  2:会员
			pointLog.setOperationUserName(accessUser.getUserName());//操作用户名称
			
			pointLog.setPoint(systemSetting.getTopic_rewardPoint());//积分
			pointLog.setUserName(accessUser.getUserName());//用户名称
			pointLog.setRemark("");
			//增加用户积分
			userService.addUserPoint(accessUser.getUserName(),systemSetting.getTopic_rewardPoint(), pointManage.createPointLogObject(pointLog));

			//用户动态
			UserDynamic userDynamic = new UserDynamic();
			userDynamic.setId(userDynamicManage.createUserDynamicId(accessUser.getUserId()));
			userDynamic.setUserName(accessUser.getUserName());
			userDynamic.setModule(100);//模块 100.话题
			userDynamic.setTopicId(topic.getId());
			userDynamic.setPostTime(topic.getPostTime());
			userDynamic.setStatus(topic.getStatus());
			userDynamic.setFunctionIdGroup(","+topic.getId()+",");
			Object new_userDynamic = userDynamicManage.createUserDynamicObject(userDynamic);
			userService.saveUserDynamic(new_userDynamic);

			
			//删除缓存
			userManage.deleteCacheFindUserById(accessUser.getUserId());
			userManage.deleteCacheFindUserByUserName(accessUser.getUserName());
			followManage.delete_cache_userUpdateFlag(accessUser.getUserName());
			topicManage.deleteCacheMarkUpdateTopicStatus(topic.getId());//删除 标记修改话题状态
			String fileNumber = "b"+ accessUser.getUserId();
			List<String> mediaNameList = filterContent.getMediaNames();
			if(CollectionUtils.isNotEmpty(mediaNameList)){//是否含有音视频
				List<MediaProcessQueue> mediaProcessQueueList = new ArrayList<MediaProcessQueue>();
				for(String fullPathName :mediaNameList){//是否含有音视频
					//取得路径名称
					String pathName = FileUtil.getFullPath(fullPathName);
					//文件名称
					String fileName = FileUtil.getName(fullPathName);
					
					MediaProcessQueue mediaProcessQueue = new MediaProcessQueue();
					mediaProcessQueue.setModule(10);//10:话题
					mediaProcessQueue.setType(10);//10:视频
					mediaProcessQueue.setParameter(String.valueOf(topic.getId()));
					mediaProcessQueue.setPostTime(topic.getPostTime());
					mediaProcessQueue.setFilePath("file/topic/"+pathName);
					mediaProcessQueue.setFileName(fileName);
					mediaProcessQueueList.add(mediaProcessQueue);
				}
				mediaProcessService.saveMediaProcessQueueList(mediaProcessQueueList);
			}
			List<String> imageNameList = filterContent.getImageNames();
			//删除图片锁
			if(CollectionUtils.isNotEmpty(imageNameList)){//图片文件列表
				for(String imageName :imageNameList){
					 if(imageName != null && !"".equals(imageName.trim())){
						//如果验证不是当前用户上传的文件，则不删除锁
						 if(!topicManage.getFileNumber(FileUtil.getBaseName(imageName.trim())).equals(fileNumber)){
							 continue;
						 }
						 fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,imageName.replaceAll("/","_"));
					 }
				}
			}
			//falsh
			List<String> flashNameList = filterContent.getFlashNames();
			if(CollectionUtils.isNotEmpty(flashNameList)){
				for(String flashName :flashNameList){
					 if(flashName != null && !"".equals(flashName.trim())){
						//如果验证不是当前用户上传的文件，则不删除锁
						if(!topicManage.getFileNumber(FileUtil.getBaseName(flashName.trim())).equals(fileNumber)){
							continue;
						}
						fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,flashName.replaceAll("/","_"));
					 }
				}
			}
			//音视频
			if(mediaNameList != null && mediaNameList.size() >0){
				for(String mediaName :mediaNameList){
					if(mediaName != null && !"".equals(mediaName.trim())){
						//如果验证不是当前用户上传的文件，则不删除锁
						if(!topicManage.getFileNumber(FileUtil.getBaseName(mediaName.trim())).equals(fileNumber)){
							continue;
						}
						fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,mediaName.replaceAll("/","_"));
					
					}
				}
			}
			//文件
			List<String> fileNameList = filterContent.getFileNames();
			if(CollectionUtils.isNotEmpty(fileNameList)){
				for(String fileName :fileNameList){
					if(fileName != null && !"".equals(fileName.trim())){
						//如果验证不是当前用户上传的文件，则不删除锁
						if(!topicManage.getFileNumber(FileUtil.getBaseName(fileName.trim())).equals(fileNumber)){
							continue;
						}
						fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,fileName.replaceAll("/","_"));
					
					}
				}
			}
			
			List<Thumbnail> thumbnailList = thumbnailService.findAllThumbnailCache();
			if(thumbnailList != null && thumbnailList.size() >0){
				//异步增加缩略图
				if(beforeImageList != null && beforeImageList.size() >0){
					fileManage.addThumbnail(thumbnailList,beforeImageList);
				}
			}
			
			//统计每分钟原来提交次数
			Integer original = settingManage.getSubmitQuantity("topic", accessUser.getUserName());
    		if(original != null){
    			settingManage.addSubmitQuantity("topic", accessUser.getUserName(),original+1);//刷新每分钟原来提交次数
    		}else{
    			settingManage.addSubmitQuantity("topic", accessUser.getUserName(),1);//刷新每分钟原来提交次数
    		}

		}
		
		
		Map<String,String> returnError = new HashMap<String,String>();//错误
		if(error.size() >0){
			//将枚举数据转为错误提示字符
    		for (Map.Entry<String,String> entry : error.entrySet()) {		 
    			if(ErrorView.get(entry.getValue()) != null){
    				returnError.put(entry.getKey(),  ErrorView.get(entry.getValue()));
    			}else{
    				returnError.put(entry.getKey(),  entry.getValue());
    			}
			}
		}
		if(isAjax == true){
			
    		Map<String,Object> returnValue = new HashMap<String,Object>();//返回值
    		
    		if(error != null && error.size() >0){
    			returnValue.put("success", "false");
    			returnValue.put("error", returnError);
    			if(captchaResult.getData()){
    				returnValue.put("captchaKey", UUIDUtil.getUUID32());
    			}
    			
    		}else{
    			returnValue.put("success", "true");
    		}
    		WebUtil.writeToWeb(JsonUtils.toJSONString(returnValue), "json", response);
			return null;
		}else{
			if(error != null && error.size() >0){//如果有错误
				redirectAttrs.addFlashAttribute("error", returnError);//重定向传参
				redirectAttrs.addFlashAttribute("topic", topic);
				

				String referer = request.getHeader("referer");	
				
				
				referer = StringUtils.removeStartIgnoreCase(referer,Configuration.getUrl(request));//移除开始部分的相同的字符,不区分大小写
				referer = StringUtils.substringBefore(referer, ".");//截取到等于第二个参数的字符串为止
				referer = StringUtils.substringBefore(referer, "?");//截取到等于第二个参数的字符串为止
				
				String queryString = request.getQueryString() != null && !"".equals(request.getQueryString().trim()) ? "?"+request.getQueryString() :"";

				return "redirect:/"+referer+queryString;
	
			}
			
			if(jumpUrl != null && !"".equals(jumpUrl.trim())){
				String url = Base64.decodeBase64URL(jumpUrl.trim());
				
				return "redirect:"+url;
			}else{//默认跳转
				model.addAttribute("message", "保存话题成功");
				String referer = request.getHeader("referer");
				if (RefererCompare.compare(request, "login")) {//如果是登录页面则跳转到首页
					referer = Configuration.getUrl(request);
				}
				model.addAttribute("urlAddress", referer);

				String dirName = templateService.findTemplateDirCache();


				return "templates/" + dirName + "/" + accessSourceDeviceManage.accessDevices(request) + "/jump";
			}
		}
	}
	
	
	
	/**
	 * 话题  修改
	 * @param model
	 * @param topicId 话题Id
	 * @param title 标题
	 * @param content 内容
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/edit", method=RequestMethod.POST)
	public String edit(ModelMap model,@RequestParam Long topicId,@RequestParam String title,@RequestParam String content,
			String token,String captchaKey,String captchaValue,String jumpUrl,
			RedirectAttributes redirectAttrs,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		//获取登录用户
		AccessUser accessUser = AccessUserThreadLocal.get(session);

		boolean isAjax = WebUtil.submitDataMode(request);//是否以Ajax方式提交数据
		Map<String, String> error = new HashMap<String, String>();
		ApiResult apiResult = systemActAccessService.access(accessUser,"topic",request,topicId);
		if(!apiResult.isSuccess()){
			if (isAjax == true) {
				response.setStatus(403);//设置状态码
				WebUtil.writeToWeb("", "json", response);
				return null;
			} else {
				String dirName = templateService.findTemplateDirCache();
				String accessPath = accessSourceDeviceManage.accessDevices(request);
				request.setAttribute("message", "权限不足");
				return "templates/" + dirName + "/" + accessPath + "/message";
			}
		}

		//判断令牌
		csrfTokenAccessService.access(accessUser,"topic",request,token);
		
		//验证码
		ApiResult<Boolean> captchaResult = captchaAccessService.access(accessUser,"topic",request,captchaKey,captchaValue);
		
		//旧图片地址
		List<ImageInfo> oldBeforeImageList = new ArrayList<ImageInfo>();
		//前3张图片地址
		List<ImageInfo> beforeImageList = new ArrayList<ImageInfo>();

		List<String> oldPathFileList = new ArrayList<String>();//旧路径文件
		
		
		Topic topic = null;
		//旧状态
		Integer oldStatus = -1;
		
		String oldContent = "";
		
		List<String> imageNameList = null;
		boolean isImage = false;//是否含有图片
		List<String> flashNameList = null;
		boolean isFlash = false;//是否含有Flash
		List<String> mediaNameList = null;
		boolean isMedia = false;//是否含有音视频
		List<String> fileNameList = null;
		boolean isFile = false;//是否含有文件
		boolean isMap = false;//是否含有地图
		
		
		if(topicId != null && topicId >0L){
			topic = topicService.findById(topicId);
			if(topic != null){
				if (!topic.getUserName().equals(accessUser.getUserName())) {
					error.put("topic", ErrorView._113.name());//只允许修改自己发布的话题
				}
				if (topic.getStatus() > 100) {
					error.put("topic", ErrorView._114.name());//话题已删除
				}

				//是否有当前功能操作权限
				boolean flag_permission = userRoleManage.isPermission(ResourceEnum._1003000, topic.getTagId(), accessUser);
				if (flag_permission == false) {
					if (isAjax == true) {
						response.setStatus(403);//设置状态码

						WebUtil.writeToWeb("", "json", response);
						return null;
					} else {
						String dirName = templateService.findTemplateDirCache();

						String accessPath = accessSourceDeviceManage.accessDevices(request);
						request.setAttribute("message", "权限不足");
						return "templates/" + dirName + "/" + accessPath + "/message";
					}
				}

				oldStatus = topic.getStatus();
				oldContent = topic.getContent();
				if(topic.getImage() != null && !"".equals(topic.getImage().trim())){
					oldBeforeImageList = JsonUtils.toGenericObject(topic.getImage().trim(),new TypeReference< List<ImageInfo> >(){});
				}
				
				
			}else{
				error.put("topic", ErrorView._112.name());//话题不存在
			}
		
		}else{
			error.put("topic", ErrorView._103.name());//话题Id不能为空
		}

		SystemSetting systemSetting = settingService.findSystemSettingCache();
		if(error.size() ==0){
			if(topic.getStatus().equals(20)){//如果已发布，则重新执行发贴审核逻辑
				//前台发表话题审核状态
				if(systemSetting.getTopic_review().equals(10)){//10.全部审核 20.特权会员未触发敏感词免审核(未实现) 30.特权会员免审核 40.触发敏感词需审核(未实现) 50.无需审核
					topic.setStatus(10);//10.待审核 	
				}else if(systemSetting.getTopic_review().equals(30)){
					if(topic.getTagId() != null && topic.getTagId() >0L){
						//是否有当前功能操作权限
						boolean isPermission = userRoleManage.isPermission(ResourceEnum._1006000, topic.getTagId(), accessUser);
						if (isPermission) {
							topic.setStatus(20);//20.已发布
						} else {
							topic.setStatus(10);//10.待审核 
						}
					}
				}else{
					topic.setStatus(20);//20.已发布
				}
			}
			if(title != null && !"".equals(title.trim())){
				if(systemSetting.isAllowFilterWord()){
					String wordReplace = "";
					if(systemSetting.getFilterWordReplace() != null){
						wordReplace = systemSetting.getFilterWordReplace();
					}
					title = sensitiveWordFilterManage.filterSensitiveWord(title, wordReplace);
				}
				
				topic.setTitle(title);
				if(title.length() >150){
					error.put("title", "不能大于150个字符");
				}
			}else{
				error.put("title", "标题不能为空");
			}
			
			if(content != null && !"".equals(content.trim())){
				EditorTag editorTag = settingManage.readTopicEditorTag();
				//过滤标签
				content = textFilterManage.filterTag(request, content, editorTag);
				FilterContent filterContent = textFilterManage.filter(request, content, "topic", editorTag, HtmlTypeEnum.ALL);
				String value = filterContent.getContent();
				imageNameList = filterContent.getImageNames();
				isImage = filterContent.isImage();//是否含有图片

				flashNameList = filterContent.getFlashNames();
				isFlash = filterContent.isFlash();//是否含有Flash
				mediaNameList = filterContent.getMediaNames();
				isMedia = filterContent.isMedia();//是否含有音视频
				fileNameList = filterContent.getFileNames();
				isFile = filterContent.isFile();//是否含有文件
				isMap = filterContent.isMap();//是否含有地图

				List<UserGrade> userGradeList = userGradeService.findAllGradeCache();
				//校正隐藏标签
				String validValue = textFilterManage.correctionHiddenTag(value, userGradeList);

				//允许使用的隐藏标签
				List<Integer> allowHiddenTagList = new ArrayList<Integer>();
				if (editorTag.isHidePassword()) {
					//是否有当前功能操作权限
					boolean _flag_permission = userRoleManage.isPermission(ResourceEnum._1020000, topic.getTagId(), accessUser);
					if (_flag_permission) {
						//输入密码可见
						allowHiddenTagList.add(HideTagType.PASSWORD.getName());
					}
				}
				if(editorTag.isHideComment()){
					//是否有当前功能操作权限
					boolean _flag_permission = userRoleManage.isPermission(ResourceEnum._1021000, topic.getTagId(), accessUser);
					if (_flag_permission) {
						//评论话题可见
						allowHiddenTagList.add(HideTagType.COMMENT.getName());
					}
				}
				if(editorTag.isHideGrade()){
					//是否有当前功能操作权限
					boolean _flag_permission = userRoleManage.isPermission(ResourceEnum._1022000, topic.getTagId(), accessUser);
					if (_flag_permission) {
						//达到等级可见
						allowHiddenTagList.add(HideTagType.GRADE.getName());
					}
				}
				if(editorTag.isHidePoint()){
					//是否有当前功能操作权限
					boolean _flag_permission = userRoleManage.isPermission(ResourceEnum._1023000, topic.getTagId(), accessUser);
					if (_flag_permission) {
						//积分购买可见
						allowHiddenTagList.add(HideTagType.POINT.getName());
					}
				}
				if(editorTag.isHideAmount()){
					//是否有当前功能操作权限
					boolean _flag_permission = userRoleManage.isPermission(ResourceEnum._1024000, topic.getTagId(), accessUser);
					if (_flag_permission) {
						//余额购买可见
						allowHiddenTagList.add(HideTagType.AMOUNT.getName());
					}
				}

				//解析隐藏标签
				Map<Integer,Object> analysisHiddenTagMap = textFilterManage.analysisHiddenTag(validValue);
				for (Map.Entry<Integer,Object> entry : analysisHiddenTagMap.entrySet()) {
					if(!allowHiddenTagList.contains(entry.getKey())){
						error.put("content", "发表话题不允许使用 '"+HideTagName.getKey(entry.getKey())+"' 隐藏标签");//隐藏标签
						break;
					}
				}
				
				//删除隐藏标签
				String newContent = textFilterManage.deleteHiddenTag(value);

				//不含标签内容
				String text = textFilterManage.filterText(textFilterManage.specifyHtmlTagToText(newContent));
				//清除空格&nbsp;
				String trimSpace = cms.utils.StringUtil.replaceSpace(text).trim();
				//摘要
				if(trimSpace != null && !"".equals(trimSpace)){
					if(systemSetting.isAllowFilterWord()){
						String wordReplace = "";
						if(systemSetting.getFilterWordReplace() != null){
							wordReplace = systemSetting.getFilterWordReplace();
						}
						trimSpace = sensitiveWordFilterManage.filterSensitiveWord(trimSpace, wordReplace);
					}
					if(trimSpace.length() >180){
						topic.setSummary(trimSpace.substring(0, 180)+"..");
					}else{
						topic.setSummary(trimSpace+"..");
					}
				}
				
				//不含标签内容
				String source_text = textFilterManage.filterText(content);
				//清除空格&nbsp;
				String source_trimSpace = cms.utils.StringUtil.replaceSpace(source_text).trim();
				
				if(isImage == true || isFlash == true || isMedia == true || isFile==true ||isMap== true || (!"".equals(source_text.trim()) && !"".equals(source_trimSpace))){
					if(systemSetting.isAllowFilterWord()){
						String wordReplace = "";
						if(systemSetting.getFilterWordReplace() != null){
							wordReplace = systemSetting.getFilterWordReplace();
						}
						validValue = sensitiveWordFilterManage.filterSensitiveWord(validValue, wordReplace);
					}
					topic.setContent(validValue);
				}else{
					error.put("content", "话题内容不能为空");
				}	
				
				
				//非隐藏标签内图片
				List<String> otherImageNameList = textFilterManage.readImageName(newContent,"topic");
				
				if(otherImageNameList != null && otherImageNameList.size() >0){
					for(int i=0; i<otherImageNameList.size(); i++){
						ImageInfo imageInfo = new ImageInfo();
						imageInfo.setName(FileUtil.getName(otherImageNameList.get(i)));
						imageInfo.setPath(FileUtil.getFullPath(otherImageNameList.get(i)));
						
						beforeImageList.add(imageInfo);
						
					}
					topic.setImage(JsonUtils.toJSONString(beforeImageList));
					
				}
			}else{
				error.put("content", "话题内容不能为空");
			}
		}
		
		if(error.size() == 0){
			topic.setLastUpdateTime(new Date());//最后修改时间
			int i = topicService.updateTopic2(topic);
			//更新索引
			topicIndexService.addTopicIndex(new TopicIndex(String.valueOf(topic.getId()),2));
			
			if(i >0 && topic.getStatus() < 100 && !oldStatus.equals(topic.getStatus())){
				User user = userManage.queryCacheFindUserByUserName(topic.getUserName());
				if (user != null) {
					//修改用户动态话题状态
					userService.updateUserDynamicTopicStatus(user.getId(), topic.getUserName(), topic.getId(), topic.getStatus());
				}

			}

			if(i >0){
				//删除缓存
				topicManage.deleteTopicCache(topic.getId());//删除话题缓存
				topicManage.delete_cache_analysisHiddenTag(topic.getId());//删除解析隐藏标签缓存
				topicManage.delete_cache_analysisFullFileName(topic.getId());//删除 解析上传的文件完整路径名称缓存
				topicManage.deleteCacheMarkUpdateTopicStatus(topic.getId());//删除 标记修改话题状态
				Object[] obj = textFilterManage.readPathName(oldContent,"topic");
				if(obj != null && obj.length >0){
					//旧图片
					List<String> old_imageNameList = (List<String>)obj[0];
					
					if(old_imageNameList != null && old_imageNameList.size() >0){
						
				        Iterator<String> iter = old_imageNameList.iterator();
				        while (iter.hasNext()) {
				        	String imageName = iter.next();  
				        	
							for(String new_imageName : imageNameList){
								if(imageName.equals("file/topic/"+new_imageName)){
									iter.remove();
									break;
								}
							}
						}
						if(old_imageNameList != null && old_imageNameList.size() >0){
							for(String imageName : old_imageNameList){
								
								oldPathFileList.add(FileUtil.toSystemPath(imageName));
		
							}
							
						}
					}
					
					//旧Flash
					List<String> old_flashNameList = (List<String>)obj[1];		
					if(old_flashNameList != null && old_flashNameList.size() >0){		
				        Iterator<String> iter = old_flashNameList.iterator();
				        while (iter.hasNext()) {
				        	String flashName = iter.next();  
							for(String new_flashName : flashNameList){
								if(flashName.equals("file/topic/"+new_flashName)){
									iter.remove();
									break;
								}
							}
						}
						if(old_flashNameList != null && old_flashNameList.size() >0){
							for(String flashName : old_flashNameList){
								oldPathFileList.add(FileUtil.toSystemPath(flashName));
								
							}
							
						}
					}

					//旧影音
					List<String> old_mediaNameList = (List<String>)obj[2];	
					if(old_mediaNameList != null && old_mediaNameList.size() >0){		
				        Iterator<String> iter = old_mediaNameList.iterator();
				        while (iter.hasNext()) {
				        	String mediaName = iter.next();  
							for(String new_mediaName : mediaNameList){
								if(mediaName.equals("file/topic/"+new_mediaName)){
									iter.remove();
									break;
								}
							}
						}
						if(old_mediaNameList != null && old_mediaNameList.size() >0){
							for(String mediaName : old_mediaNameList){
								oldPathFileList.add(FileUtil.toSystemPath(mediaName));
								
							}
							
						}
					}
					
					//旧文件
					List<String> old_fileNameList = (List<String>)obj[3];		
					if(old_fileNameList != null && old_fileNameList.size() >0){		
				        Iterator<String> iter = old_fileNameList.iterator();
				        while (iter.hasNext()) {
				        	String fileName = iter.next();  
							for(String new_fileName : fileNameList){
								if(fileName.equals("file/topic/"+new_fileName)){
									iter.remove();
									break;
								}
							}
						}
						if(old_fileNameList != null && old_fileNameList.size() >0){
							for(String fileName : old_fileNameList){
								oldPathFileList.add(FileUtil.toSystemPath(fileName));
								
							}
							
						}
					}
				}
				List<Thumbnail> thumbnailList = thumbnailService.findAllThumbnailCache();
				if(thumbnailList != null && thumbnailList.size() >0){
					if(oldBeforeImageList != null && oldBeforeImageList.size() >0){
						List<ImageInfo> deleteBeforeImageList = new ArrayList<ImageInfo>();
						A:for(ImageInfo oldImageInfo : oldBeforeImageList){
							if(beforeImageList != null && beforeImageList.size() >0){
								for(ImageInfo imageInfo : beforeImageList){
									if(oldImageInfo.getName().equals(imageInfo.getName())){
										continue A;
									}
								}
							}
							deleteBeforeImageList.add(oldImageInfo);
						}
						if(deleteBeforeImageList != null && deleteBeforeImageList.size() >0){
							//删除旧缩略图
							fileManage.deleteThumbnail(thumbnailList,oldBeforeImageList);
						}
					}
					
					//异步增加缩略图
					if(beforeImageList != null && beforeImageList.size() >0){
						fileManage.addThumbnail(thumbnailList,beforeImageList);
					}
				}
				
				//上传文件编号
				String fileNumber = topicManage.generateFileNumber(topic.getUserName(), topic.getIsStaff());
				
				//删除图片锁
				if(imageNameList != null && imageNameList.size() >0){
					for(String imageName :imageNameList){
				
						 if(imageName != null && !"".equals(imageName.trim())){
							 //如果验证不是当前用户上传的文件，则不删除
							 if(!topicManage.getFileNumber(FileUtil.getBaseName(imageName.trim())).equals(fileNumber)){
									continue;
							 }
							 fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,imageName.replaceAll("/","_"));
		
						 }
					}
				}
				//删除Falsh锁
				if(flashNameList != null && flashNameList.size() >0){
					for(String flashName :flashNameList){
						 
						 if(flashName != null && !"".equals(flashName.trim())){
							 //如果验证不是当前用户上传的文件，则不删除
							 if(!topicManage.getFileNumber(FileUtil.getBaseName(flashName.trim())).equals(fileNumber)){
									continue;
							 }
							 fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,flashName.replaceAll("/","_"));
			
						 }
					}
				}
				//删除音视频锁
				if(mediaNameList != null && mediaNameList.size() >0){
					for(String mediaName :mediaNameList){
						if(mediaName != null && !"".equals(mediaName.trim())){
							//如果验证不是当前用户上传的文件，则不删除
							if(!topicManage.getFileNumber(FileUtil.getBaseName(mediaName.trim())).equals(fileNumber)){
								continue;
							}
							fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,mediaName.replaceAll("/","_"));
						
						}
					}
				}
				//删除文件锁
				if(fileNameList != null && fileNameList.size() >0){
					for(String fileName :fileNameList){
						if(fileName != null && !"".equals(fileName.trim())){
							//如果验证不是当前用户上传的文件，则不删除
							if(!topicManage.getFileNumber(FileUtil.getBaseName(fileName.trim())).equals(fileNumber)){
								continue;
							}
							fileManage.deleteLock("file"+File.separator+"topic"+File.separator+"lock"+File.separator,fileName.replaceAll("/","_"));
						
						}
					}
				}
				
				//删除旧路径文件
				if(oldPathFileList != null && oldPathFileList.size() >0){
					for(String oldPathFile :oldPathFileList){
						
						//如果验证不是当前用户上传的文件，则不删除
						if(!topicManage.getFileNumber(FileUtil.getBaseName(oldPathFile.trim())).equals(fileNumber)){
							continue;
						}
						//替换路径中的..号
						oldPathFile = FileUtil.toRelativePath(oldPathFile);
						
						//删除旧路径文件
						Boolean state = fileManage.deleteFile(oldPathFile);
						if(state != null && state == false){

							//替换指定的字符，只替换第一次出现的
							oldPathFile = StringUtils.replaceOnce(oldPathFile, "file"+File.separator+"topic"+File.separator, "");
							oldPathFile = StringUtils.replace(oldPathFile, File.separator, "_");//替换所有出现过的字符
							
							//创建删除失败文件
							fileManage.failedStateFile("file"+File.separator+"topic"+File.separator+"lock"+File.separator+oldPathFile);
						}
					}
				}

			}else{
				error.put("topic", ErrorView._115.name());//修改话题失败
			}
		}
		Map<String,String> returnError = new HashMap<String,String>();//错误
		if(error.size() >0){
			//将枚举数据转为错误提示字符
    		for (Map.Entry<String,String> entry : error.entrySet()) {		 
    			if(ErrorView.get(entry.getValue()) != null){
    				returnError.put(entry.getKey(),  ErrorView.get(entry.getValue()));
    			}else{
    				returnError.put(entry.getKey(),  entry.getValue());
    			}
			}
		}
		if(isAjax == true){
			
    		Map<String,Object> returnValue = new HashMap<String,Object>();//返回值
    		
    		if(error != null && error.size() >0){
    			returnValue.put("success", "false");
    			returnValue.put("error", returnError);
    			if(captchaResult.getData()){
    				returnValue.put("captchaKey", UUIDUtil.getUUID32());
    			}
    			
    		}else{
    			returnValue.put("success", "true");
    		}
    		WebUtil.writeToWeb(JsonUtils.toJSONString(returnValue), "json", response);
			return null;
		}else{
			if(error != null && error.size() >0){//如果有错误
				
				redirectAttrs.addFlashAttribute("error", returnError);//重定向传参
				redirectAttrs.addFlashAttribute("topic", topic);
				String referer = request.getHeader("referer");
				referer = StringUtils.removeStartIgnoreCase(referer,Configuration.getUrl(request));//移除开始部分的相同的字符,不区分大小写
				referer = StringUtils.substringBefore(referer, ".");//截取到等于第二个参数的字符串为止
				referer = StringUtils.substringBefore(referer, "?");//截取到等于第二个参数的字符串为止
				
				String queryString = request.getQueryString() != null && !"".equals(request.getQueryString().trim()) ? "?"+request.getQueryString() :"";

				return "redirect:/"+referer+queryString;
	
			}
			
			
			if(jumpUrl != null && !"".equals(jumpUrl.trim())){
				String url = Base64.decodeBase64URL(jumpUrl.trim());
				
				return "redirect:"+url;
			}else{//默认跳转
				model.addAttribute("message", "修改话题成功");
				String referer = request.getHeader("referer");
				if (RefererCompare.compare(request, "login")) {//如果是登录页面则跳转到首页
					referer = Configuration.getUrl(request);
				}
				model.addAttribute("urlAddress", referer);

				String dirName = templateService.findTemplateDirCache();


				return "templates/" + dirName + "/" + accessSourceDeviceManage.accessDevices(request) + "/jump";
			}
		}
	}

	/**
	 * 文件上传
	 * dir: 上传类型，分别为image、file、media
	 * 
	 * 员工发话题 上传文件名为UUID + a + 员工Id
	 * 用户发话题 上传文件名为UUID + b + 用户Id
	 */
	@RequestMapping(value="/upload", method=RequestMethod.POST)
	@ResponseBody//方式来做ajax,直接返回字符串
	public String upload(ModelMap model,@RequestParam String dir,
			MultipartFile file,HttpServletRequest request, HttpServletResponse response)  {

		Map<String, Object> returnJson = new HashMap<String, Object>();
		//获取登录用户
		AccessUser accessUser = AccessUserThreadLocal.get(session);
		ApiResult apiResult = systemActAccessService.access(accessUser,"topic",request,null);
		Map<String, String> error = new HashMap<String, String>();
		String errorMessage = "";
		if(!apiResult.isSuccess()){
			errorMessage = "不允许提交数据";
		}else if(file != null && !file.isEmpty()){
			ApiResult<String> rt = SpringContextHolder.getBean(dir+"BeService", FileService.class).upload(file,accessUser,"topic",dir);
			if(rt.isSuccess()) {
				//上传成功
				returnJson.put("error", 0);//0成功  1错误
				returnJson.put("url", rt.getData());
				return JsonUtils.toJSONString(returnJson);
			}else{
				//上传失败
				returnJson.put("error", 1);
				returnJson.put("message", rt.getMessage());
				return JsonUtils.toJSONString(returnJson);
			}
		}else{
			errorMessage = "文件内容不能为空";
		}
		//上传失败
		returnJson.put("error", 1);
		returnJson.put("message", errorMessage);
		return JsonUtils.toJSONString(returnJson);
	}

	/**
	 * 话题  取消隐藏
	 * @param model
	 * @param topicId 话题Id
	 * @param hideType 隐藏类型
	 * @param password 密码
	 * @param token
	 * @param jumpUrl
	 * @param redirectAttrs
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/unhide", method=RequestMethod.POST)
	public String topicUnhide(ModelMap model,@RequestParam Long topicId,@RequestParam Integer hideType, String password,
			String token,String jumpUrl,
			RedirectAttributes redirectAttrs,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Assert.isTrue(topicId>0,"topicId参数错误");
		//获取登录用户
		AccessUser accessUser = AccessUserThreadLocal.get(session);

		ApiResult apiResult = systemActAccessService.access(accessUser,"topic",request,topicId);
		Map<String, String> error = new HashMap<String, String>();
		Topic topic = null;
		if(!apiResult.isSuccess()){
			error.put("topicUnhide", ErrorView._21.name());//只读模式不允许提交数据
		}else {
			//判断令牌
			csrfTokenAccessService.access(accessUser,"topic",request,token);
			submitQuantityAccessService.access(accessUser,"topic",request,"Unhide");

			topic = topicManage.queryTopicCache(topicId);//查询缓存
			if(topic != null) {
				//话题取消隐藏Id
				String topicUnhideId = topicManage.createTopicUnhideId(accessUser.getUserId(), hideType, topicId);
				TopicUnhide topicUnhide = topicManage.queryCacheFindTopicUnhideById(topicUnhideId);
				if (topicUnhide != null) {
					error.put("topicUnhide", ErrorView._1610.name());//当前话题已经取消隐藏
				}
				if (topic.getUserName().equals(accessUser.getUserName())) {
					error.put("topicUnhide", ErrorView._1690.name());//不允许解锁自已发表的话题
				}
				if (MapUtils.isEmpty(error)) {
					//解析隐藏标签
					Map<Integer, Object> analysisHiddenTagMap = textFilterManage.analysisHiddenTag(topic.getContent());
					if (MapUtils.isNotEmpty(analysisHiddenTagMap)) {
						Object value = analysisHiddenTagMap.get(hideType);
						User user = null;
						HideTagType tagType = HideTagType.buildByName(hideType);
						Assert.notNull(tagType, ErrorView._1620.name());//隐藏标签不存在
						switch (tagType) {
							case GRADE:
								break;
							case PASSWORD://密码可见
								if (StringUtils.equals((value + ""), password)) {
									topicUnhide = topicUnhideBuild(accessUser, hideType, topic, topicUnhideId);
									accountManage.use(tagType, topicUnhide, accessUser, topic);
								} else {
									error.put("topicUnhide", ErrorView._1630.name());//密码错误
								}
								break;
							case POINT://积分购买可见
								//获取登录用户
								user = userService.findUserById(accessUser.getUserId());
								if (user != null) {
									Long point = (Long) value;
									if (user.getPoint() < point) {
										error.put("topicUnhide", ErrorView._1680.name());//用户积分不足
									} else {
										topicUnhide = topicUnhideBuild(accessUser, hideType, topic, topicUnhideId);
										topicUnhide.setPoint(point);
										accountManage.use(tagType, topicUnhide, accessUser, topic);
									}
								} else {
									error.put("topicUnhide", ErrorView._1670.name());//用户不存在
								}
								break;
							case AMOUNT: {//余额购买可见
								//获取登录用户
								user = userService.findUserById(accessUser.getUserId());
								if (user != null) {
									BigDecimal amount = (BigDecimal) value;
									if (user.getDeposit().compareTo(amount) < 0) {
										error.put("topicUnhide", ErrorView._1685.name());//用户余额不足
									} else {
										topicUnhide = topicUnhideBuild(accessUser, hideType, topic, topicUnhideId);
										topicUnhide.setAmount(amount);
										accountManage.use(tagType, topicUnhide, accessUser, topic);
									}
								} else {
									error.put("topicUnhide", ErrorView._1670.name());//用户不存在
								}
								break;
							}
							default:
						}
						if (MapUtils.isEmpty(error)) {
							//删除'话题取消隐藏'缓存;
							topicManage.deleteCacheFindTopicUnhideById(topicUnhideId);
							//删除用户缓存
							userManage.deleteCacheFindUserById(accessUser.getUserId());
							userManage.deleteCacheFindUserByUserName(accessUser.getUserName());
						}
					}
				}
			}
		}

		if(error.size() == 0){
			try {
				User _user = userManage.queryCacheFindUserByUserName(topic.getUserName());
				//别人解锁了我的话题  只对(隐藏标签类型 10:输入密码可见  40:积分购买可见  50:余额购买可见)发提醒
				if (!topic.getIsStaff() && _user != null && !topic.getUserName().equals(accessUser.getUserName())) {//不发提醒给自己
					//提醒楼主
					Remind remind = new Remind();
					remind.setId(remindManage.createRemindId(_user.getId()));
					remind.setReceiverUserId(_user.getId());//接收提醒用户Id
					remind.setSenderUserId(accessUser.getUserId());//发送用户Id
					remind.setTypeCode(60);//60:别人解锁了我的话题
					remind.setSendTimeFormat(new Date().getTime());//发送时间格式化
					remind.setTopicId(topic.getId());//话题Id
					Object remindObject = remindManage.createRemindObject(remind);
					remindService.saveRemind(remindObject);
					//删除提醒缓存
					remindManage.deleteCacheFindUnreadRemindByUserId(_user.getId());
				}
			} catch (org.springframework.orm.jpa.JpaSystemException e) {
				error.put("topicUnhide", ErrorView._1600.name());//话题重复取消隐藏
			}
		}
		
		Map<String,String> returnError = new HashMap<String,String>();//错误
		if(error.size() >0){
			//将枚举数据转为错误提示字符
    		for (Map.Entry<String,String> entry : error.entrySet()) {		 
    			if(ErrorView.get(entry.getValue()) != null){
    				returnError.put(entry.getKey(),  ErrorView.get(entry.getValue()));
    			}else{
    				returnError.put(entry.getKey(),  entry.getValue());
    			}
			}
		}
		boolean isAjax = WebUtil.submitDataMode(request);//是否以Ajax方式提交数据
		if(isAjax){
    		Map<String,Object> returnValue = new HashMap<String,Object>();//返回值
    		if(error != null && error.size() >0){
    			returnValue.put("success", "false");
    			returnValue.put("error", returnError);
    			
    		}else{
    			returnValue.put("success", "true");
    		}
    		WebUtil.writeToWeb(JsonUtils.toJSONString(returnValue), "json", response);
			return null;
		}else{
			if(error != null && error.size() >0){//如果有错误
				redirectAttrs.addFlashAttribute("error", returnError);//重定向传参
				redirectAttrs.addFlashAttribute("hideType", hideType);
				String referer = request.getHeader("referer");	

				referer = StringUtils.removeStartIgnoreCase(referer,Configuration.getUrl(request));//移除开始部分的相同的字符,不区分大小写
				referer = StringUtils.substringBefore(referer, ".");//截取到等于第二个参数的字符串为止
				referer = StringUtils.substringBefore(referer, "?");//截取到等于第二个参数的字符串为止
				
				String queryString = request.getQueryString() != null && !"".equals(request.getQueryString().trim()) ? "?"+request.getQueryString() :"";

				return "redirect:/"+referer+queryString;
	
			}
			if(jumpUrl != null && !"".equals(jumpUrl.trim())){
				String url = Base64.decodeBase64URL(jumpUrl.trim());
				return "redirect:"+url;
			}else{//默认跳转
				model.addAttribute("message", "话题取消隐藏成功");
				String referer = request.getHeader("referer");
				if (RefererCompare.compare(request, "login")) {//如果是登录页面则跳转到首页
					referer = Configuration.getUrl(request);
				}
				model.addAttribute("urlAddress", referer);
				String dirName = templateService.findTemplateDirCache();
				return "templates/" + dirName + "/" + accessSourceDeviceManage.accessDevices(request) + "/jump";
			}
		}
	}

	/**
	 * 构建话题取消隐藏对象
	 * @param accessUser
	 * @param hideType
	 * @param topic
	 * @param topicUnhideId
	 * @return
	 */
	private TopicUnhide topicUnhideBuild(AccessUser accessUser, Integer hideType, Topic topic, String topicUnhideId) {
		TopicUnhide topicUnhide = new TopicUnhide();
		topicUnhide.setId(topicUnhideId);
		topicUnhide.setUserName(accessUser.getUserName());
		topicUnhide.setCancelTime(new Date());
		topicUnhide.setHideTagType(hideType);
		topicUnhide.setPostUserName(topic.getUserName());//发布话题的用户名称
		topicUnhide.setTopicId(topic.getId());
		return  topicUnhide;
	}

}
